package com.cn.esermis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisQueueService {

    @Autowired
    private ListOperations<String, Object> listOps;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void sendMessage(String queueKey, Object message) {
        listOps.rightPush(queueKey, message);
    }

    public boolean isQueueEmpty(String queueKey) {
        Long size = listOps.size(queueKey);
        return size == 0;
    }

    public Object receiveMessage(String queueKey) {

        return listOps.leftPop(queueKey);
    }

    public void addElementWithExpire(String key, String element, long expireTime, TimeUnit timeUnit) {
        // 将元素添加到 Hash 中
        redisTemplate.opsForHash().put("dataKey:"+key, element, element);
        // 设置过期时间
        redisTemplate.expire("dataKey:"+key, expireTime, timeUnit);
    }

    public boolean isElementExist(String key, String element) {
        // 检查元素是否存在
        return redisTemplate.opsForHash().hasKey("dataKey:"+key, element);
    }

    public void removeElement(String key, String element) {
        // 删除元素
        redisTemplate.opsForHash().delete("dataKey:"+key, element);
    }

    // 存储数字
    public void setNumber(String key, long value) {
        redisTemplate.opsForValue().set(key, String.valueOf(value));
    }

    // 获取数字
    public Long getNumber(String key) {
        String value = redisTemplate.opsForValue().get(key);
        return value != null ? Long.parseLong(value) : 0;
    }

}